
import sql from '@/utils/sqlLite.js'
import {
	setObjSql,
	obj2str_sql,
	encryption,
	decrypt
} from '@/utils/index.js'
// 数据表名称  价格表
export const price = 'priceDemo'
export const database = uni.getStorageSync('database')
/*

productModel 品类Id
priceGroup 价格组
agencySecurityDeposit 代理押金
priceModel 价格模板
commission 代理提成比例
*/
export const cratePriceTable = async () => {
	let sqltxt = [
		`create table if not exists ${price}("productModel" VARCHAR(128),"priceGroup" VARCHAR(256))`,
	];
	let res = await sql.executeSQL(uni.getStorageSync('database'), sqltxt);
	console.log(res);
}

// 添加价格
export const addPrice = async (pushData) => {

	// 数据库中productModel 存在 修改 ，不存在 新增
	let productModel = encryption(pushData.productModel)
	console.log(productModel);
	let sqltxt = `select *from ${price} where productModel = '${productModel}'`;
	let res = await sql.selectSQL(uni.getStorageSync('database'), sqltxt);
	console.log(res);
	if (res.code == 0 && res.data.length == 0) { //数据库中没有数据 新增

		let condition = Object.keys(pushData).join(',')
		let data = setObjSql(pushData)
		console.log(condition,data);
		
		let sqltxt = `INSERT  INTO ${price} (${condition}) VALUES(${data})`
		return await sql.executeSQL(uni.getStorageSync('database'), sqltxt);

	} else { //存在 ，更改
		let data = obj2str_sql(pushData)
		let sqltxt = `update  ${price} set ${data} where productModel = '${productModel}'`
		let rrs =  await sql.executeSQL(uni.getStorageSync('database'), sqltxt);
		console.log(rrs);
	}
}

// 获取productModel对应的详情
export const getPriceTypeToId = async (productModel) => {
	let model = encryption(productModel)
	let sqltxt = `select * from ${price} where productModel = '${model}'`;
	let datas = await sql.selectSQL(uni.getStorageSync('database'), sqltxt);
	console.log(datas);
	datas.data.forEach(item =>{
		for (const key in item) {
			item[key] = decrypt(item[key])
		}
	})
	return datas

}